import requests
import json
from datetime import datetime
from app.models import Message2, MessageThread2  # 导入您的模型
 # Amazon SP API 配置
SP_API_URL = "https://sellingpartnerapi-na.amazon.com"  # 根据区域调整
REFRESH_TOKEN = "your_refresh_token"
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
ROLE_ARN = "your_role_arn"

def get_access_token():
    # 获取访问令牌的函数
    url = "https://api.amazon.com/auth/o2/token"
    payload = {
        'grant_type': 'refresh_token',
        'refresh_token': REFRESH_TOKEN,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET
    }
    response = requests.post(url, data=payload)
    return response.json().get('access_token')

def sync_messages():
    access_token = get_access_token()
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json',
        'x-amz-access-token': access_token
    }

    # 获取所有消息
    response = requests.get(f"{SP_API_URL}/messaging/v1/orders", headers=headers)
    messages = response.json().get('messages', [])

    for message in messages:
        message_id = message['messageId']
        content = message['content']
        sender = message['sender']
        thread_id = message['threadId']
        
        # 检查是否已同步
        if not Message2.objects.filter(message_id=message_id).exists():
            # 创建新的消息记录
            Message2.objects.create(
                message_id=message_id,
                content=content,
                sender=sender,
                thread=MessageThread2.objects.get(thread_id=thread_id)  # 假设您有相应的线程
            )
        else:
            # 更新状态（例如，关闭状态）
            existing_message = Message2.objects.get(message_id=message_id)
            if message['status'] != existing_message.is_read:
                existing_message.is_read = message['status']
                existing_message.save()

if __name__ == "__main__":
    sync_messages()